const Router = require("koa-router");
const { Auth } = require("@middlewares/auth");
const { pay, wxPay } = require("@services/pay");
const { Enroll } = require("@models/enroll");
const { Refund } = require("@models/refund");

const router = new Router({
  prefix: "/admin/wxpay",
});

router.post("/notify", async (ctx, next) => {
  console.log("微信支付");
  const body = ctx.request.body; // 微信请求你的回调接口的实体类 body
  const headers = ctx.request.headers; // 微信请求你的回调接口的 headers
  // 支付回调验证签名
  const result = await wxPay.verifySignature(body, headers);

  if (result.code !== 200) {
    ctx.body = result;
  }
  // 回调解密
  const data = await wxPay.decrypt(body);
  if (data.code !== 200) {
    ctx.body = data;
  }

  const res = JSON.parse(data.data);
  const enroll = await Enroll.findOne({
    where: {
      enroll_number: res.out_trade_no,
    },
  });
  if (!enroll) {
    ctx.body = { code: 401, msg: "订单不存在" };
  }
  // console.log("回调解密:" + JSON.stringify(res));
  // 退款回调
  //  res = {
  //    mchid: "1683029327",
  //    out_trade_no: "OTN17249592844142168",
  //    transaction_id: "4200002436202408304717259430",
  //    out_refund_no: "ORN17249594412346753",
  //    refund_id: "50310100552024083004606235101",
  //    refund_status: "SUCCESS",
  //    success_time: "2024-08-30T03:24:04+08:00",
  //    amount: { total: 1, refund: 1, payer_total: 1, payer_refund: 1 },
  //    user_received_account: "支付用户零钱",
  //  };

  // 支付成功
  // res = {
  //   mchid: "1683029327",
  //   appid: "wx94da07422597ebc2",
  //   out_trade_no: "OTN17249566916289203",
  //   transaction_id: "4200002401202408301703112103",
  //   trade_type: "JSAPI",
  //   trade_state: "SUCCESS",
  //   trade_state_desc: "支付成功",
  //   bank_type: "OTHERS",
  //   attach: "",
  //   success_time: "2024-08-30T02:38:18+08:00",
  //   payer: { openid: "oRmEh7fbFuLerIskcE2JqCCEYQsI" },
  //   amount: {
  //     total: 1,
  //     payer_total: 1,
  //     currency: "CNY",
  //     payer_currency: "CNY",
  //   },
  // };

  let status = (res) => {
    if (res.trade_state === "SUCCESS") {
      // SUCCESS：支付成功
      // REFUND：转入退款
      // NOTPAY：未支付
      // CLOSED：已关闭
      // REVOKED：已撤销（付款码支付）
      // USERPAYING：用户支付中（付款码支付）
      // PAYERROR：支付失败(其他原因，如银行返回失败)
      return 1; // 已支付
    }
    if (res.refund_status === "SUCCESS") {
      // SUCCESS：退款成功
      // CLOSED：退款关闭
      // ABNORMAL：退款异常，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，可前往【商户平台—>交易中心】，手动处理此笔退款
      return -1; // 已退款
    }
  };
  // 更新订单状态
  await Enroll.update(
    { enroll_status: status(res) },
    {
      where: {
        enroll_number: res.out_trade_no,
      },
    }
  );

  ctx.body = { code: 200 };
});

router.post("/refund", new Auth(16).m, async (ctx, next) => {
  const { enroll_id } = ctx.request.body;

  const enroll = await Enroll.findOne({
    where: {
      enroll_id,
    },
  });

  let enroll_info = JSON.parse(JSON.stringify(enroll));

  const refund = await Refund.create({
    out_trade_no: enroll_info.enroll_number,
    reason: "系统退款",
    refund: 1, // 退款金额，单位为分
    total: 1, // 订单总金额，单位为分
  });

  const info = JSON.parse(JSON.stringify(refund));

  let params = {
    out_trade_no: info.out_trade_no,
    out_refund_no: info.out_refund_no,
    reason: "系统退款",
    notify_url: "https://cellsplus.top/admin/wxpay/notify",
    amount: {
      refund: parseInt(info.refund), // 退款金额，单位为分
      total: parseInt(info.total), // 订单总金额，单位为分
      currency: "CNY",
    },
  };

  const res = await pay.refunds(params);
  await enroll.update({
    enroll_status: 3, //退款中
  });
  let status = {
    SUCCESS: 1, // 退款成功
    CLOSED: -1, // 退款关闭
    PROCESSING: 0, // 退款处理中
    ABNORMAL: 2, // 退款异常
  };

  await refund.update(
    { refund_status: status[res.data.status] }, // 1:已支付
    {
      where: {
        out_trade_no: refund.out_trade_no,
      },
    }
  );
  ctx.body = {
    code: 200,
  };
});

module.exports = router;
